//
//  UserLoginController.m
//  华康通
//
//  Created by leiyu on 16/9/12.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "UserLoginController.h"
#import "PhoneRegistController.h"
#import "ResetKeyController.h"
#import "UMMobClick/MobClick.h"
#import "DLWTH5Controller.h"

static NSString* textStr;

@interface UserLoginController ()<UITextFieldDelegate>

//上下输入框之间的线（在切换手机登录和密码登录的时候改变颜色）
@property (strong, nonatomic) IBOutlet UIView *centerView;

@property (strong, nonatomic) IBOutlet UIButton *isHiddenKeyButton;

//使用语音接收验证码
@property (strong, nonatomic) IBOutlet UIButton *voiceButton;
//收不到验证码
@property (strong, nonatomic) IBOutlet UILabel *voiceLabel;

//输入工号或手机号码的输入框
@property (strong, nonatomic) IBOutlet UITextField *topTextField;
//输入密码
@property (strong, nonatomic) IBOutlet UITextField *bottomTextField;
//验证码显示的label
@property (strong, nonatomic) IBOutlet UILabel *coreLabel;
//登录按钮
@property (strong, nonatomic) IBOutlet UIButton *loginButton;
//快速注册
//@property (strong, nonatomic) IBOutlet UIButton *registButton;
//忘记密码
@property (strong, nonatomic) IBOutlet UIButton *forgetKeyButton;
@property (strong, nonatomic) IBOutlet UIView *keyCenterView;
//获取验证码 按钮
@property (strong, nonatomic) IBOutlet UIButton *codeButton;
//登录按钮的状态label
@property (strong, nonatomic) IBOutlet UILabel *showLoginLabel;
@property (unsafe_unretained, nonatomic) NSInteger buttonIndex;

//放一个时间记录器 来记录 验证码的时间
@property (nonatomic, strong) NSTimer* timer;
//记录时间
@property (nonatomic, unsafe_unretained) NSInteger count;
//延迟请求后台数据的bool值
@property (nonatomic, unsafe_unretained) BOOL isSelected;

@property (nonatomic, strong) ZTVertyStatus* vertyStatus;

//后台返回回来的验证码
@property (nonatomic, strong) NSString* verificationCode;
//是否显示密码
@property (nonatomic, unsafe_unretained) BOOL isHiddenKey;
//用户用手机登录的时候先记录用户的当前输入的手机号码
@property (nonatomic, strong) NSString* myUserPhone;


@end

@implementation UserLoginController

//登陆遇到问题 进到本地h5页面
//- (IBAction)goToWebView:(UIButton *)sender
//{
//    DLWTH5Controller* h5 = [[DLWTH5Controller alloc]initWithNibName:@"DLWTH5Controller" bundle:nil];
//    h5.html = [NSString stringWithFormat:@"%@/static/faq/index.html",DLWTURL];
//    h5.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:h5 animated:YES];
//}

- (ZTVertyStatus*)vertyStatus
{
    if (!_vertyStatus)
    {
        _vertyStatus = [[ZTVertyStatus alloc]init];
    }
    return _vertyStatus;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.isHiddenKey = YES;
    self.isSelected = NO;
    self.buttonIndex = 0;
    


    self.showLoginLabel.layer.cornerRadius = 6.0;
    self.showLoginLabel.layer.masksToBounds = YES;

}
- (IBAction)back:(id)sender
{
    [self popRootVC];
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self setNeedsStatusBarAppearanceUpdate];
    self.count = 90;
    [MobClick beginLogPageView:@"UserLoginController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    self.navigationController.navigationBar.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self setNeedsStatusBarAppearanceUpdate];
    [MobClick endLogPageView:@"UserLoginController"];
}

- (void)viewDidDisappear:(BOOL)animated
{
    //停止计时器
    [self.timer invalidate];
    self.timer = nil;
    self.coreLabel.text = @"获取验证码";
    self.coreLabel.textColor = KMainColor;
    //重新获取按钮可以用
    self.codeButton.enabled = YES;
    [self.bottomTextField setText:nil];
}

//使用语音接收验证码
- (IBAction)voiceVerity:(UIButton *)sender
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    if (self.verificationCode)
    {
        NSDictionary* json = @{@"platformType":@"1",
                               @"orderType":@"01",
                               @"requestService":@"ttsVerifyCodeCall",
                               @"requestObject":@{@"operateType":@"4",
                                                  @"operateCode":self.topTextField.text ,
                                                  @"validateCode":self.verificationCode,
                                                  @"mobile":self.topTextField.text
                                                  }
                               };
        //字符串转字符串
        NSString* str = [JSONToString dictionaryToJson:json];
        //转md5
        MyAdditions* md5 = [[MyAdditions alloc]init];
        md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
        NSString* md5_Str = [md5 md5];
        NSLog(@"转md5之前时的字符串:%@",[NSString stringWithFormat:@"%@%@",KEY_POST,str]);
        NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
        NSLog(@"语音接收验证码url = %@  json字典 ＝ %@",url,json);
        
        HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
        [networking showErrorWithSuccess:^{
            
            [XHNetworking POST:url parameters:json success:^(NSData *responseObject) {
                id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
                NSLog(@"语音接收验证码json = %@",json);
                if ([json isKindOfClass:[NSDictionary class]] && json)
                {
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        if ([json[@"responseObject"][@"result"] isEqualToString:@"0"])
                        {
                            NSLog(@"语音接收验证码成功");
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [self showAlertViewWithMsg:[NSString stringWithFormat:@"语音发送验证码成功，请留意接听"]];
                            });
                        }
                        else
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                                [statusBar showStatusMessage:[NSString stringWithFormat:@"%@",json[@"errorMessage"]]];
                            });
                        }
                    });
                    
                    
                }
            } failure:^(NSError *error) {
                NSLog(@"error.code = %@",error.userInfo);
                dispatch_async(dispatch_get_main_queue(), ^{
                    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                    [statusBar showStatusMessage:@"语音发送验证码失败!"];
                });
                if (error.code == -1001)
                {
                    NSLog(@"网络请求超时.....................");
                }
            }];
            
        } failure:^{
            //展示广告图
            NSLog(@"检测到设备无网络连接！！！");
            dispatch_async(dispatch_get_main_queue(), ^{
                XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];
            });
        }];
        
    }
    else
    {
        [self showAlertViewWithMsg:[NSString stringWithFormat:@"服务端错误"]];
    }
}

//时间纪录
- (void)recordTime:(NSTimer*)timer
{
    self.count--;
    self.coreLabel.text = [NSString stringWithFormat:@"重新发送(%ldS)",(long)self.count];
    self.coreLabel.textColor = LLCColor;
    if (self.count <= 0)
    {
        self.coreLabel.textColor = KMainColor;
        self.coreLabel.text = @"重新获取";
        self.count = 90;
        //停止计时器
        [self.timer invalidate];
        //重新获取按钮可以用
        self.codeButton.enabled = YES;
        
    }
    else
    {
        //重新获取按钮不可以用
        self.codeButton.enabled = NO;
    }
}

//当点击获取验证码时显示语音接收验证码
- (void)showVoiceButton
{
    self.voiceLabel.hidden = NO;
    self.voiceButton.hidden = NO;
}

//隐藏语音接收验证码
- (void)hideVoiceButton
{
    self.voiceLabel.hidden = YES;
    self.voiceButton.hidden = YES;
}
//点击获取验证码
- (IBAction)getPhoneCode:(id)sender
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    
    [self showVoiceButton];
    __weak  UserLoginController *wself = self;
    //如果是手机登录
    if (self.buttonIndex == 1)
    {
        //如果有输入手机号码
        if (![self.topTextField.text isEqualToString:@""] && self.topTextField.text)
        {
            //验证手机号码的有效性
            if ([ExamineTool verityPhoneWithString:self.topTextField.text])
            {
                NSLog(@"手机号码填写正确!");
                self.codeButton.enabled = NO;
                //重启计时器
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTime:) userInfo:nil repeats:YES];
                NSDictionary* json = @{@"platformType":@"1",
                                       @"orderType":@"01",
                                       @"requestService":@"sendSmsVerifyCode",
                                       @"requestObject":@{@"operateType":@"4",
                                                          @"operateCode":self.topTextField.text ,
                                                          @"recommendCode":@"nAduW",
                                                          @"mobile":self.topTextField.text
                                                          }
                                       };
                //字符串转字符串
                NSString* str = [JSONToString dictionaryToJson:json];
                //转md5
                MyAdditions* md5 = [[MyAdditions alloc]init];
                md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
                NSString* md5_Str = [md5 md5];
                NSLog(@"转md5之前时的字符串:%@",[NSString stringWithFormat:@"%@%@",KEY_POST,str]);
                NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
                NSLog(@"发送验证码url = %@  json字典 ＝ %@",url,json);
                [self postVerificationCodeWithURL:url withParam:json];
            }
            else
            {
//                [self presentAlerControllerWithMessage:@"您手机号码无效！请重新输入" withTextField:wself.topTextField];
                
                ShowAlertView(@"您手机号码无效！请重新输入",wself.topTextField);
            }
        }
        else
        {
//            [self presentAlerControllerWithMessage:@"您还未输入手机号码！" withTextField:wself.topTextField];
            
            ShowAlertView(@"您还未输入手机号码！",wself.topTextField);
        }
    }
}
//是否显示密码
- (IBAction)isHiddenKey:(UIButton *)sender
{
    if (self.isHiddenKey)
    {
        self.bottomTextField.secureTextEntry = NO;
        [sender setImage:LoadImage(@"iconland16") forState:UIControlStateNormal];
    }
    else
    {
        self.bottomTextField.secureTextEntry = YES;
        [sender setImage:LoadImage(@"iconland15") forState:UIControlStateNormal];
    }
    self.isHiddenKey = !self.isHiddenKey;
}
- (IBAction)keyOrYZLogin:(UISegmentedControl *)sender
{
    if (sender.selectedSegmentIndex == 0)
    {
        //密码登陆
        [self.topTextField resignFirstResponder];
        [self.bottomTextField resignFirstResponder];
        [self hideVoiceButton];
        self.buttonIndex = 0;
        [self.topTextField setText:nil];
        [self.bottomTextField setText:nil];
        [self judeColor];
        
        [self.keyCenterView setHidden:YES];
        [self.coreLabel setHidden:YES];
        [self.codeButton setHidden:YES];
        self.codeButton.enabled = NO;
        self.topTextField.placeholder = @"请输入您的手机号码/工号";
        self.bottomTextField.placeholder = @"请输入密码";
        self.topTextField.keyboardType = UIKeyboardTypeEmailAddress;
        self.bottomTextField.keyboardType = UIKeyboardTypeEmailAddress;
        self.bottomTextField.secureTextEntry = YES;
        [self.isHiddenKeyButton  setImage:LoadImage(@"iconland15") forState:UIControlStateNormal];
        self.coreLabel.text = @"获取验证码";
        self.count = 90;
        //停止计时器
        [self.timer invalidate];
        self.isHiddenKeyButton.hidden = NO;
    }
    else
    {
        //验证码登陆
        [self.topTextField resignFirstResponder];
        [self.bottomTextField resignFirstResponder];
        [self hideVoiceButton];
        self.buttonIndex = 1;
        [self.topTextField setText:nil];
        [self.bottomTextField setText:nil];
        [self judeColor];
        [self.keyCenterView setHidden:NO];
        [self.coreLabel setHidden:NO];
        [self.codeButton setHidden:NO];
        self.codeButton.enabled = YES;
        self.coreLabel.textColor = KMainColor;
        self.topTextField.placeholder = @"请输入您的手机号";
        self.bottomTextField.placeholder = @"请输入验证码";
        self.topTextField.keyboardType = UIKeyboardTypePhonePad;
        self.bottomTextField.keyboardType = UIKeyboardTypePhonePad;
        self.bottomTextField.secureTextEntry = NO;
        self.isHiddenKeyButton.hidden = YES;
    }
}



//按下去就变色
- (IBAction)showLabelColorChange:(UIButton *)sender
{
    if (![self.topTextField.text isEqualToString:@""] && ![self.bottomTextField.text isEqualToString:@""])
    {
        self.showLoginLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:1.0];
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            
            self.showLoginLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
            });
    }
}

//判断按钮背景的颜色
- (void)judeColor
{
    if (![self.topTextField.text isEqualToString:@""] && ![self.bottomTextField.text isEqualToString:@""])
    {
        self.showLoginLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
    }
    else
    {
        self.showLoginLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:0.1];
    }
}

- (void)vercityTrueForLoginWithInterger:(NSInteger)index
{
    __weak  UserLoginController *wself = self;
    if (index == 0)
    {
        //非纯字母或者纯数字 高于8位
        if ([ExamineTool verityKeyWithString:self.bottomTextField.text])
        {
            
            if (self.isSelected)
            {
                return;
            }
            self.isSelected = YES;
            [self performSelector:@selector(timeEnough) withObject:nil afterDelay:1.2];
        }
        //纯字母或者纯数字 或者少于8位
        else
        {
//            [self presentAlerControllerWithMessage:@"密码不符合规范！请重新输入" withTextField:wself.bottomTextField];
            
            ShowAlertView(@"密码不符合规范！请重新输入",wself.bottomTextField);
        }
    }
    else
    {
        //纯数字 并且是6位
        if (self.bottomTextField.text.length >=4 && self.bottomTextField.text.length <=6 && [ExamineTool isPureNumandCharacters:wself.bottomTextField.text])
        {
            if (self.isSelected)
            {
                return;
            }
            self.isSelected = YES;
            [self performSelector:@selector(timeEnough) withObject:nil afterDelay:1.2];
        }
        else
        {
            
//            [self presentAlerControllerWithMessage:@"验证码不符合规范！请重新输入" withTextField:wself.bottomTextField];
            
            ShowAlertView(@"验证码不符合规范！请重新输入",wself.bottomTextField);
        }
    }
}

//系统提示框
- (void)presentAlerControllerWithMessage:(NSString*)message withTextField:(UITextField*)textField
{
    NSLog(@"%@",message);
    [self.view endEditing:YES];
    
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = message;
//    customView.layer.cornerRadius = 7.0;
//    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", @"取消", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                [textField becomeFirstResponder];
            break;
            default:
                NSLog(@"取消操作" );
            break;
        }
    }];
    [alertView show];
}

//登录
- (IBAction)login:(UIButton *)sender
{
    NSLog(@"登录。。。。");
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    if (![self.topTextField.text isEqualToString:@""] && ![self.bottomTextField.text isEqualToString:@""])
    {
        [self.view endEditing:YES];
        if (self.buttonIndex == 0)
        {
            //验证是否为工号或手机号码
            if ([ExamineTool verityPhoneWithString:self.topTextField.text] || [ExamineTool isUserCodeWithStr:self.topTextField.text])
            {
                //验证工号/手机号码输入框
                [self vercityTrueForLoginWithInterger:self.buttonIndex];
            }
            else
            {
//                [self presentAlerControllerWithMessage:@"您输入的工号/手机号码不合法！请重新输入" withTextField:self.topTextField];
                
                ShowAlertView(@"您输入的工号/手机号码不合法！请重新输入",self.topTextField);
            }
        }
        else
        {
            //验证是否为手机号码
            if ([ExamineTool verityPhoneWithString:self.topTextField.text])
            {
                //手机号码输入框
                [self vercityTrueForLoginWithInterger:self.buttonIndex];
            }
            else
            {
//                [self presentAlerControllerWithMessage:@"您输入的手机号码有误！" withTextField:self.topTextField];
                
                ShowAlertView(@"您输入的手机号码有误！",self.topTextField);
            }
        }
    }
}


#pragma mark  //发送验证码
- (void)postVerificationCodeWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"发送验证码json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"responseObject"][@"result"] isEqualToString:@"0"])
                {
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        self.verificationCode = json[@"responseObject"][@"verificationCode"];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
                            TextStatusView *customView  = [TextStatusView view];
                            customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
                            customView.bottomLabel.text = @"验证码已发送";
                            [alertView setContainerView:customView];
                            [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", nil]];
                            [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
                                switch (buttonIndex)
                                {
                                    case 0:
                                        [self.bottomTextField becomeFirstResponder];
                                        return ;
                                        break;
                                    default:
                                        return ;
                                        break;
                                }
                            }];
                            [alertView show];
                        });
                    });
                    
                    
                }
                else
                {
                    if (![json[@"errorMessage"] isEqualToString:@""] && json[@"errorMessage"])
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                            [statusBar showStatusMessage:[NSString stringWithFormat:@"%@",json[@"errorMessage"]]];
                        });
                    }
                    if (![json[@"responseObject"][@"msg"] isEqualToString:@""] && json[@"responseObject"][@"msg"])
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                            [statusBar showStatusMessage:[NSString stringWithFormat:@"%@",json[@"responseObject"][@"msg"]]];
                        });
                    }
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"error.code = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                [statusBar showStatusMessage:@"发送验证码失败！"];
            });
            if (error.code == -1001)
            {
                NSLog(@"网络请求超时.....................");
            }
        }];
        self.myUserPhone = self.topTextField.text;
        
    } failure:^{
        //展示广告图
        NSLog(@"检测到设备无网络连接！！！");
        dispatch_async(dispatch_get_main_queue(), ^{
            XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
            [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];
        });
    }];
    
}

- (void)postLoginMessageWithURL:url withParam:json
{
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        
        [XHNetworking POST:url parameters:json cacheStr:@"UserLogin" jsonCache:^(id jsonCache) {
            id result = [NSJSONSerialization JSONObjectWithData:jsonCache options:0 error:nil];
            NSLog(@"登录信息本地缓存信息jsonCache = %@",result);
            //先从缓存读取缓存信息;
            
        } success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"用户登录json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"responseObject"] isKindOfClass:[NSDictionary class]])
                {
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        if ([json[@"responseObject"][@"loginResult"] isEqualToString:@"0"])
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                __weak UserLoginController* wself = self;
                                self.vertyStatus.status = ^(NSInteger vertyStatus,NSInteger second)
                                {
                                    NSLog(@"vertyStatus = %ld,second = %ld",(long)vertyStatus,(long)second);
                                    if (second == 1 && vertyStatus == 0)
                                    {
                                        NSLog(@"执行跳转到首页的操作....");
                                        [wself.navigationController popToRootViewControllerAnimated:YES];
                                    }
                                };
                                [self.vertyStatus createVertyStatusViewWithMessage:@"恭喜您登录成功\n页面即将跳转到个人中心..." withPushType:0 withReturnStatus:^(NSInteger vertyStatus, NSInteger second) {
                                    [self.topTextField resignFirstResponder];
                                    [self.bottomTextField resignFirstResponder];
                                }];
                            });
                        }
                        else
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                                [statusBar showStatusMessage:[NSString stringWithFormat:@"%@",json[@"responseObject"][@"resultMessage"]]];
                            });
                        }
                    });
                    
                    
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                        [statusBar showStatusMessage:@"登陆失败，账号异常"];
                    });
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"error.code = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                [statusBar showStatusMessage:@"登陆失败，请重试！"];
            });
            if (error.code == -1001)
            {
                NSLog(@"网络请求超时.....................");
            }
        }];
        
    } failure:^{
        //展示广告图
        NSLog(@"检测到设备无网络连接！！！");
        dispatch_async(dispatch_get_main_queue(), ^{
            XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
            [statusBar showStatusMessage:@"检测到您的设备没有连接网络!"];
        });
    }];
    
}

- (void)showAlertViewWithMsg:(NSString*)msg
{
    dispatch_async(dispatch_get_main_queue(), ^{
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
        TextStatusView *customView  = [TextStatusView view];
        customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
        customView.bottomLabel.text = msg;
        //    customView.layer.cornerRadius = 7.0;
        //    customView.layer.masksToBounds = YES;
        [alertView setContainerView:customView];
        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", nil]];
        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
            switch (buttonIndex)
            {
                case 0:
                    [self.bottomTextField setText:nil];
                    return ;
                    break;
                default:
                    return ;
                    break;
            }
        }];
        [alertView show];
    });
}

- (void)timeEnough
{
    //正式填写与后台的交互....
    if (self.buttonIndex == 1)
    {
        if ([self.topTextField.text isEqualToString:self.myUserPhone])
        {
            if (self.verificationCode)
            {
                //如果填写的验证码和系统返回的验证码一样
                if ([self.bottomTextField.text isEqualToString:self.verificationCode])
                {
                    //手机登录
                    NSDictionary* json = @{@"platformType":@"1",
                                           @"orderType":@"01",
                                           @"requestService":@"login",
                                           @"requestObject":@{@"customerName":self.topTextField.text,
                                                              @"password":@"" ,
                                                              @"verificationCode":self.bottomTextField.text,
                                                              @"loginType":@"2"
                                                              }
                                           };
                    //字符串转字符串
                    NSString* str = [JSONToString dictionaryToJson:json];
                    //转md5
                    MyAdditions* md5 = [[MyAdditions alloc]init];
                    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
                    NSString* md5_Str = [md5 md5];
                    NSLog(@"转md5之前时的字符串:%@",[NSString stringWithFormat:@"%@%@",KEY_POST,str]);
                    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
                    NSLog(@"手机登录url = %@  json字典 ＝ %@",url,json);
                    [self postLoginMessageWithURL:url withParam:json];
                }
                else
                {
                    [self showAlertViewWithMsg:[NSString stringWithFormat:@"验证码输入有误，请重新输入"]];
                }
            }
            else
            {
                [self showAlertViewWithMsg:[NSString stringWithFormat:@"请先获取验证码！"]];
                self.coreLabel.textColor = KMainColor;
                self.coreLabel.text = @"重新获取";
                self.count = 90;
                //停止计时器
                [self.timer invalidate];
                //重新获取按钮可以用
                self.codeButton.enabled = YES;
            }
        }
        else
        {
            [self showAlertViewWithMsg:[NSString stringWithFormat:@"验证码错误，请重新获取！"]];
            self.coreLabel.textColor = KMainColor;
            self.coreLabel.text = @"获取验证码";
            self.count = 90;
            //停止计时器
            [self.timer invalidate];
            //重新获取按钮可以用
            self.codeButton.enabled = YES;
        }
    }
    else
    {
        //密码登录
        NSDictionary* json = @{@"platformType":@"1",
                               @"orderType":@"01",
                               @"requestService":@"login",
                               @"requestObject":@{@"customerName":self.topTextField.text,
                                                  @"password":self.bottomTextField.text ,
                                                  @"verificationCode":@"",
                                                  @"loginType":@"1"
                                                  }
                               };
        //字符串转字符串
        NSString* str = [JSONToString dictionaryToJson:json];
        //转md5
        MyAdditions* md5 = [[MyAdditions alloc]init];
        md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
        NSString* md5_Str = [md5 md5];
        NSLog(@"转md5之前时的字符串:%@",[NSString stringWithFormat:@"%@%@",KEY_POST,str]);
        NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
        NSLog(@"手机登录url = %@  json字典 ＝ %@",url,json);
        [self postLoginMessageWithURL:url withParam:json];
    }
    
//    UIButton *btn = (UIButton *)[self.view viewWithTag:100];
    self.isSelected = NO;
}

//注册
/*
- (IBAction)regist:(UIButton *)sender
{
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PhoneRegistController* registVC=[storyboard instantiateViewControllerWithIdentifier:@"RegistVC"];
    registVC.title = @"快速注册";
    registVC.myPushType = PushRegistVC;
    [self.navigationController pushViewController:registVC animated:YES];
}
 */
//忘记密码
- (IBAction)forgetKey:(UIButton *)sender
{
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    ResetKeyController* resetVC = [storyboard instantiateViewControllerWithIdentifier:@"ResetKeyVC"];
    [self.navigationController pushViewController:resetVC animated:YES];
}

//关闭键盘
- (IBAction)closeKeyboard:(UITextField *)sender
{
    [sender resignFirstResponder];
    //点next 进入密码输入
    [self.bottomTextField becomeFirstResponder];
    //执行
    [self getPhoneCode:self.codeButton];
}

//关闭键盘
- (IBAction)closeBottomKeyboard:(UITextField *)sender
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    //点击密码键盘上的 return时  就会后台请求
    [self login:self.loginButton];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (IBAction)changeText:(UITextField *)sender
{
    if (self.buttonIndex == 1)
    {
        if (sender.text.length == 11)
        {
            textStr = sender.text;
        }
        else if (sender.text.length > 11)
        {
            sender.text = textStr;
        }
    }
    NSLog(@"最上面文字发生改变了");
    [self judeColor];
}

- (IBAction)keyChangeText:(UITextField *)sender
{
    if (self.buttonIndex == 1)
    {
        if (sender.text.length == 4)
        {
            textStr = sender.text;
        }
        else if (sender.text.length > 4)
        {
            sender.text = textStr;
        }
    }
    NSLog(@"密码输入文字发生改变了");
    [self judeColor];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"textFieldDidBeginEditing");
}
//如果输入完
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
}



@end
